package com.songlanyun.modules.usergains.controller.admin;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

//import org.apache.shiro.authz.annotation.RequiresPermissions;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.songlanyun.common.annotation.AuthIgnore;
import com.songlanyun.common.annotation.SysLog;
import com.songlanyun.common.utils.*;
import com.songlanyun.common.utils.custom.ClassConvertUtils;
import com.songlanyun.common.validator.ValidatorUtils;
import com.songlanyun.modules.shop.entity.ShopEntity;
import com.songlanyun.modules.shop.service.ShopService;
import com.songlanyun.modules.user.controller.AbstractController;
import com.songlanyun.modules.usergains.entity.UserOrderGains;
import com.songlanyun.modules.usergains.model.AirdropStatisticsVo;
import com.songlanyun.modules.usergains.model.SettlementUserOrderGainsDTO;
import com.songlanyun.modules.usergains.model.UpdateCommissionDTO;
import com.songlanyun.modules.usergains.model.UserOrderGainsVo;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.songlanyun.modules.usergains.service.UserOrderGainsService;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static org.bouncycastle.asn1.x500.style.RFC4519Style.uid;


/**
 * 会员分佣所得表
 *
 * @author wuchao
 * @email sunlightcs@gmail.com
 * @date 2020-12-22 15:21:52
 */
@RestController
@RequestMapping("admin/userordergains")
public class UserOrderGainsAdminController extends AbstractController {
    @Autowired
    private UserOrderGainsService userOrderGainsService;

    @Autowired
    private ShopService shopService;

    /**
     * 商家或平台,分页查询会员分佣所得
     * mobile 分佣人手机号,可以不给
     * order_code 订单号,可以不给
     * status 订单状态,可以不给(1未完成，2已完成，未结算，3已结算)
     * start_date 开始日期，可以不给(格式2020-12-10)
     * end_date 结束日期，可以不给(格式2020-12-10)
     * page
     * limit
     */
    @GetMapping("/pages")
    //@RequiresPermissions("usergains:distributionuserordergains:list")
    public R page(@RequestParam Map<String, Object> params) {
        if (isShop()) {
            params.put("shop_id", getShopId());//店铺
        }

        PageUtils page = userOrderGainsService.queryPage(params);
        return R.ok().put("page", page);
    }

    /**
     * 商家或平台,分页查询会员分佣所得
     * mobile 分佣人手机号,可以不给
     * order_code 订单号,可以不给
     * status 订单状态,可以不给(1未完成，2已完成，未结算，3已结算)
     * start_date 开始日期，可以不给(格式2020-12-10)
     * end_date 结束日期，可以不给(格式2020-12-10)
     * token

     */
    @GetMapping("/export")
    @AuthIgnore
    //@RequiresPermissions("usergains:distributionuserordergains:list")
    public void export(@RequestParam Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Long adminId = this.getAdminByToken(response);
        ShopEntity shop = shopService.getShopByAdminId(adminId,false);
        if(shop==null)
        {
            response.setCharacterEncoding("UTF-8"); //设置编码格式
            response.setContentType("application/json");
            R responseBean = R.error(-401, "非法操作");
            response.getWriter().write(JSON.toJSONString(responseBean));
            return;
        }

        params.put("shop_id", shop.getId());
        List<UserOrderGainsVo> userOrderGainsVos = userOrderGainsService.queryList(params);
        userOrderGainsVos.forEach(o->o.setGiveRemark());
        String fileName = "会员分佣订单" + DateUtils.format(new Date(), "yyyy-MM-dd-HHmmss")+"_"+ shop.getId()+ "." + "xls";
        ExportParams exportParams = new ExportParams("会员分佣订单导出("+userOrderGainsVos.size()+")", "会员分佣订单");

        Workbook sheets = ExcelExportUtil.exportExcel(exportParams, UserOrderGainsVo.class, userOrderGainsVos);
        response.setContentType(new MimetypesFileTypeMap().getContentType("application/octet-stream"));// 设置response内容的类型

        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));// 设置头部信息
        sheets.write(response.getOutputStream());
        sheets.close();
    }


    /**
     * 根据商家所得获取会员分佣所得
     */
    @GetMapping("/list/{shopGainsId}")
    //@RequiresPermissions("usergains:distributionuserordergains:list")
    public R list(@PathVariable("shopGainsId") Long shopGainsId) {

        List<UserOrderGains> list = userOrderGainsService.loadByShopGains(getShopId(true),shopGainsId);
        return R.ok().put("list", list);
    }


    /**
     * 平台商家手动结算282，6750，差价分佣
     * 选择的会员分佣订单必须是282，6750，差价分佣，必需是已完成，未结算的会员分佣订单
     */
    @SysLog("平台商家手动结算282，6750，差价分佣")
    @PostMapping("/settlement")
    //@RequiresPermissions("usergains:distributionuserordergains:info")
    public R settlement(@RequestBody SettlementUserOrderGainsDTO dto) {
        userOrderGainsService.manualSettlement(getShopId(true),dto);
        return R.ok();
    }

    /**
     * 增加或减少会员的贡献值
     * @param dto
     * @return
     */
    @PostMapping("/update/commission")
    //@RequiresPermissions("usergains:distributionuserordergains:info")
    public R updateCommission(@RequestBody UpdateCommissionDTO dto) {
        ValidatorUtils.validateEntity(dto);
        userOrderGainsService.updateCommission(getUser(),dto);
        return R.ok();
    }


    /**
     *
     * @return
     */
    @GetMapping("/airdropStatistics")
    //@RequiresPermissions("usergains:distributionuserordergains:list")
    public R airdropStatistics() {
        AirdropStatisticsVo vo = userOrderGainsService.airdropStatistics();
        return R.ok().put("data", vo);
    }

}
